<?php
function get($url)
{
    $ch = curl_init();
    //设置选项包括URL
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_HEADER,0);
    //执行并获取HTML文档内容
    $output=curl_exec($ch);
    //释放curl句柄
    curl_close($ch);
    //打印获得的数据
    return mb_convert_encoding($output,'utf-8','gbk'); 
}

// function post($url,$post_data=[])
// { 
//     $ch = curl_init();
//     curl_setopt($ch, CURLOPT_URL, $url);
//     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//     // post数据
//     curl_setopt($ch, CURLOPT_POST, 1);
//     // post的变量
//     curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
//     $output = curl_exec($ch);
//     curl_close($ch);
//     //打印获得的数据
//     print_r($output);
// }
 
// 账户日志
function regScoreLog($userid,$account,$desc)
{ 
    if (!$userid) {
        return ;
    }
    $res=db('account_log')->insert([
        'userid'=>$userid,
        'type'=>0,
        'account'=>$account,
        'desc'=>$desc,
        'c_account'=>db('member')->where("id=".$userid)->value('reg_score')+$account,
        'create_time'=>time()
    ]);
    if ($res) {
        db('member')->where('id='.$userid)->setInc('reg_score',$account);
        // 会员总额增加
        if ($account>0) {
            db('member')->where('id='.$userid)->setInc('score_total',$account);
        }
    } 
}


function shareScoreLog($userid,$account,$desc)
{ 
    if (!$userid) {
        return ;
    } 
    $res=db('account_log')->insert([
        'userid'=>$userid,
        'type'=>1,
        'account'=>$account,
        'desc'=>$desc,
        'c_account'=>db('member')->where("id=".$userid)->value('share_score')+$account,
        'create_time'=>time()
    ]);
    if ($res) {
        db('member')->where('id='.$userid)->setInc('share_score',$account);
        // 会员总额增加
        if ($account>0) {
            db('member')->where('id='.$userid)->setInc('score_total',$account);
        }
    } 
}

function coldScoreLog($userid,$account,$desc)
{ 
    if (!$userid) {
        return ;
    }
    $res=db('account_log')->insert([
        'userid'=>$userid,
        'type'=>2,
        'account'=>$account,
        'desc'=>$desc,
        'c_account'=>db('member')->where("id=".$userid)->value('cold_score')+$account,
        'create_time'=>time()
    ]);
    if ($res) {
        db('member')->where('id='.$userid)->setInc('cold_score',$account);
        // 会员总额增加
        
        db('member')->where('id='.$userid)->setInc('score_total',$account);
         
    } 
}
/**
 * 加密函数
 * @param string $txt 需要加密的字符串
 * @param string $key 密钥
 * @return string 返回加密结果
 */
function encrypt($txt, $key = ''){
    if (empty($txt)) return $txt;
    if (empty($key)) $key = md5('cqzmdkkdakdakjdkadakdahkadhakdhaidaodjahd45484815');
    $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.";
    $ikey ="-x6g6ZWm2G9g_vr0Bo.pOq3kRIxsZ6rm";
    $nh1 = rand(0,64);
    $nh2 = rand(0,64);
    $nh3 = rand(0,64);
    $ch1 = $chars{$nh1};
    $ch2 = $chars{$nh2};
    $ch3 = $chars{$nh3};
    $nhnum = $nh1 + $nh2 + $nh3;
    $knum = 0;$i = 0;
    while(isset($key{$i})) $knum +=ord($key{$i++});
    $mdKey = substr(md5(md5(md5($key.$ch1).$ch2.$ikey).$ch3),$nhnum%8,$knum%8 + 16);
    $txt = base64_encode(time().'_'.$txt);
    $txt = str_replace(array('+','/','='),array('-','_','.'),$txt);
    $tmp = '';
    $j=0;$k = 0;
    $tlen = strlen($txt);
    $klen = strlen($mdKey);
    for ($i=0; $i<$tlen; $i++) {
        $k = $k == $klen ? 0 : $k;
        $j = ($nhnum+strpos($chars,$txt{$i})+ord($mdKey{$k++}))%64;
        $tmp .= $chars{$j};
    }
    $tmplen = strlen($tmp);
    $tmp = substr_replace($tmp,$ch3,$nh2 % ++$tmplen,0);
    $tmp = substr_replace($tmp,$ch2,$nh1 % ++$tmplen,0);
    $tmp = substr_replace($tmp,$ch1,$knum % ++$tmplen,0);
    return $tmp;
}
/**
 * 解密函数
 * @param string $txt 需要解密的字符串
 * @param string $key 密匙
 * @return string 字符串类型的返回结果
 */
function decrypt($txt, $key = '', $ttl = 0){
    if (empty($txt)) return $txt;
    if (empty($key)) $key = md5('cqzmdkkdakdakjdkadakdahkadhakdhaidaodjahd45484815');
    $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.";
    $ikey ="-x6g6ZWm2G9g_vr0Bo.pOq3kRIxsZ6rm";
    $knum = 0;$i = 0;
    $tlen = @strlen($txt);
    while(isset($key{$i})) $knum +=ord($key{$i++});
    $ch1 = @$txt{$knum % $tlen};
    $nh1 = strpos($chars,$ch1);
    $txt = @substr_replace($txt,'',$knum % $tlen--,1);
    $ch2 = @$txt{$nh1 % $tlen};
    $nh2 = @strpos($chars,$ch2);
    $txt = @substr_replace($txt,'',$nh1 % $tlen--,1);
    $ch3 = @$txt{$nh2 % $tlen};
    $nh3 = @strpos($chars,$ch3);
    $txt = @substr_replace($txt,'',$nh2 % $tlen--,1);
    $nhnum = $nh1 + $nh2 + $nh3;
    $mdKey = substr(md5(md5(md5($key.$ch1).$ch2.$ikey).$ch3),$nhnum % 8,$knum % 8 + 16);
    $tmp = '';
    $j=0; $k = 0;
    $tlen = @strlen($txt);
    $klen = @strlen($mdKey);
    for ($i=0; $i<$tlen; $i++) {
        $k = $k == $klen ? 0 : $k;
        $j = strpos($chars,$txt{$i})-$nhnum - ord($mdKey{$k++});
        while ($j<0) $j+=64;
        $tmp .= $chars{$j};
    }
    $tmp = str_replace(array('-','_','.'),array('+','/','='),$tmp);
    $tmp = trim(base64_decode($tmp));
    if (preg_match("/\d{10}_/s",substr($tmp,0,11))){
        if ($ttl > 0 && (time() - substr($tmp,0,11) > $ttl)){
            $tmp = null;
        }else{
            $tmp = substr($tmp,11);
        }
    }
    return $tmp;
}

function getCookieUserid()
{
    $crypt_c_memberid=cookie('crt_userid');
    if ($crypt_c_memberid) {
        $crt_userid=decrypt($crypt_c_memberid);
        return $crt_userid;
    }else{
        return 0;
    } 
}

function getCookieUsername()
{
    return model('user')->where('id='.getCookieUserid())->find()->user_name;
}

 

 // 筛选
 function listFilter()
 {
    $order='id desc';
    $where="id>0";
    $param_arr=request()->except('page,order,excel,s_time,e_time');
      foreach ($param_arr as $key => $v) { 
            $between=explode('__',$param_arr[$key]);

            if (count($between)==1) {
                $where.=" and ".$key."='".$param_arr[$key]."'";
            }
            if (count($between)==2) {
                $where.=" and ".$key.">=".$between[0]." and ".$key."<=".$between[1]."";
            }  
    }
    if (request()->param('order')) {
        $order=request()->param('order');
    } 
    return [
        'where'=>$where,
        'order'=>$order
    ];
 }

 function ajaxReturn($data){
    header('Content-Type:application/json; charset=utf-8');
    exit(json_encode($data));
}

// 选择图片集封面
function getFacePhoto($pic_url)
{
   $arr=explode('||||||',$pic_url);
   $pic=$arr[0];
   if (!$pic) {
       $pic='__SHEME__/static/images/nopic.png';
   }
   return $pic;
}
 
 
// 获取网站配置
function sys()
{
    return db('sys')->find();
}

 
 

function get_rand_str($randLength=6,$addtime=1,$includenumber=0){
    if ($includenumber){
        $chars='abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQEST123456789';
    }else {
        $chars='abcdefghijklmnopqrstuvwxyz';
    }
    $len=strlen($chars);
    $randStr='';
    for ($i=0;$i<$randLength;$i++){
        $randStr.=$chars[rand(0,$len-1)];
    }
    $tokenvalue=$randStr;
    if ($addtime){
        $tokenvalue=$randStr.time();
    }
    return $tokenvalue;
}


function parse_url_param($str){
    $data = array();
    $str = explode('?',$str);
    $str = end($str);
    $parameter = explode('&',$str);
    foreach($parameter as $val){
        $tmp = explode('=',$val);
        $data[$tmp[0]] = $tmp[1];
    }
    return $data;
}

// 前面补齐0
// 
function createUsername($userid)
{
    $prev='wsfcw';
    $bit=5;
    $id_len=strlen($userid);
    $zero='';
    for ($i=0; $i <$bit-$id_len ; $i++) { 
        $zero.='0';
    }

    return $prev.$zero.$userid;
     
}

// 文件路径问题
function fileUrl($str)
{
    return str_replace('\\','/',$str);
}

function fileUrl1($str)
{
    return str_replace('/','\\',$str);
}

 
// 上传图片
function upload()
{
	$data=[];
	$file=request()->file();//返回的是一个数组
    if ($file) {
        foreach ($file as $k => $v) {
            if (is_array($file[$k])) {//多图片 
               $pic_url='';
               foreach ($file[$k] as $photo) {
                 $info=$photo->move(ROOT_PATH . 'public' . DS . 'uploads');
                 if ($info) {
                 	$pic_url.=APP_URL.'public/uploads/'.fileUrl($info->getSaveName()).'||||||';
                 } 
               }
               $data[$k]=$pic_url;
            }else{//单图片 
                $info=$file[$k]->move(ROOT_PATH . 'public' . DS . 'uploads');
                if ($info) {
                	$data[$k]=APP_URL.'public/uploads/'.fileUrl($info->getSaveName());
                }
            }
        }
    }

    return $data;
}

// 获取图片列表
function getPhotoList($pic_url,$table="",$id=0,$field="")
{
	$text='';
	$arr=explode('||||||',$pic_url);
	if (count($arr)==1) {//单图
		$text='<img src="'.$arr[0].'" width="100" />';
	}else{//多图
		foreach ($arr as $v) {
			if ($v) {
				$text.='<div><img src="'.$v.'" width="100" /><a href="'.url('api/delPhoto',['table'=>$table,'id'=>$id,'field'=>$field,'value'=>$v]).'">删除</a></div>';
			} 
		}
	}
	return $text;
}

// 返回位置
function position($text)
{
    return '<ul class="nav nav-tabs">
        <li><a href="javascript:;" class="nav-link active">'.$text.'</a></li>
    </ul>';
}


// 发送短信
//请求数据到短信接口，检查环境是否 开启 curl init。
function Post($curlPost,$url){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_NOBODY, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        $return_str = curl_exec($curl);
        curl_close($curl);
        return $return_str;
}

//将 xml数据转换为数组格式。
function xml_to_array($xml){
    $reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
    if(preg_match_all($reg, $xml, $matches)){
        $count = count($matches[0]);
        for($i = 0; $i < $count; $i++){
        $subxml= $matches[2][$i];
        $key = $matches[1][$i];
            if(preg_match( $reg, $subxml )){
                $arr[$key] = xml_to_array( $subxml );
            }else{
                $arr[$key] = $subxml;
            }
        }
    }
    return $arr;
}

//random() 函数返回随机整数。
function random($length = 6 , $numeric = 0) {
    PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
    if($numeric) {
        $hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
    } else {
        $hash = '';
        $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
        $max = strlen($chars) - 1;
        for($i = 0; $i < $length; $i++) {
            $hash .= $chars[mt_rand(0, $max)];
        }
    }
    return $hash;
}


// 验证验证码是否正确
function check_phone_code($code)
{
    $is=false;
    if ($code&&cookie('phone_code')==$code) {
       $is=true;
    }
    return $is;
}

// 返回用户名
function getUname($uid)
{
    return db('member')->where("id=".$uid)->value('user_name');
}